﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DM4;
using System.Data;
using DevExpress.XtraTreeList.Nodes;
using System.Windows.Forms;

namespace DM4Client
{

    public partial class FrmMain
    {
        private void rbiWorkRefreshItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshWork();
        }

        private void BuildWorkTreeFirstLevel()
        {
            _fWork.tlWork.BeginUnboundLoad();

            try
            {
                DataRow[] top = DtWork.Select("wType = 'M'");

                foreach (DataRow dr in top)
                {
                    TreeListNode node = _fWork.tlWork.AppendNode(
                         new object[] {
                            dr["wId"],
                            dr["wParentId"],
                            dr["wType"],
                            dr["wEntity"],
                            dr["wStart"],
                            dr["wStop"],                         
                            dr["wStatus"],
                            dr["wProgress"],
                            dr["wTraffic"],
                            dr["wUser"],
                            dr["wErrors"],
                            dr["wRecords"]
                     }, null);


                    //calc visibility for expand button                    
                    DataRow[] tasks = DtWork.Select(String.Format("wParentId = {0}", dr["wId"]));
                    node.HasChildren = tasks.Length > 0;
                }
            }
            finally { _fWork.tlWork.EndUnboundLoad(); }
        }

        private void tlWorkBeforeExpand(object sender, DevExpress.XtraTreeList.BeforeExpandEventArgs e)
        {
            TreeListNode node = e.Node;
            if (node.Tag == null || (bool)node.Tag == false)
            {
                _fWork.tlWork.BeginUpdate();
                _fWork.tlWork.BeginUnboundLoad();
                try
                {
                    DataRow[] top = DtWork.Select(String.Format("wParentId = {0}", node.GetValue(0)));

                    foreach (DataRow dr in top)
                    {
                        TreeListNode node2 = _fWork.tlWork.AppendNode(
                             new object[] {
                            dr["wId"],
                            dr["wParentId"],
                            dr["wType"],
                            dr["wEntity"],
                            dr["wStart"],
                            dr["wStop"],                            
                            dr["wStatus"],
                            dr["wProgress"],
                            dr["wTraffic"],
                            dr["wUser"],
                            dr["wErrors"],
                            dr["wRecords"]
                     }, node.Id);

                        //calc visibility for expand button
                        if (dr["wType"].ToString() == "T")
                        {
                            DataRow[] sess = DtWork.Select(String.Format("wParentId = {0}", dr["wId"]));
                            node2.HasChildren = sess.Length > 0;
                        }
                    }
                }
                finally
                {
                    _fWork.tlWork.EndUnboundLoad();
                    _fWork.tlWork.EndUpdate();
                }

                node.Tag = true;
            }

        }

        private void RefreshWork(int entity = DM4Consts.DefaultNULLId)
        {
            _fWork.tlWork.FocusedNodeChanged -= tlWorkFocusedNodeChanged;

            BeginWait();
            try
            {


                //int id = DM4Consts.DefaultNULLId;
                //if (entiryId == DM4Consts.DefaultNULLId)
                //{

                //    if (_fScripts.gvScripts.RowCount > 0)
                //    {
                //        DataRow drs = _fScripts.gvScripts.GetDataRow(_fScripts.gvScripts.FocusedRowHandle);
                //        id = SysUtils.ConvertFromDBVal<int>(drs["scr_id"]);
                //    }
                //}
                //else
                //    id = scrId;

                _fWork.tlWork.BeginUpdate();
                try
                {
                    try
                    {
                        _fWork.tlWork.Nodes.Clear();

                        //_fWork.tlWork.DataSource = null;
                        //_fWork.tlWork.KeyFieldName = "";
                        //_fWork.tlWork.ParentFieldName = "";

                        XMLInfo xi = GetWorkTree(rbiWorkAdminMode.Down);
                        if (xi.OperResult.UsrSessionId == null)
                        {
                        }

                        DtWork = XMLInfo.FillTable(xi, DtWork);

                        BuildWorkTreeFirstLevel();

                        //_fWork.tlWork.DataSource = DtWork;

                        //_fWork.tlWork.KeyFieldName = "wId";
                        //_fWork.tlWork.ParentFieldName = "wParentId";

                        //_fWork.tlWork.BestFitColumns();

                        //_fScripts.gvScripts.BeginUpdate();
                        //try
                        //{
                        //    int rowHandle = _fScripts.gvScripts.LocateByValue("scr_id", id);
                        //    // exiting the loop if no row is found 
                        //    if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                        //        _fScripts.gvScripts.FocusedRowHandle = rowHandle;
                        //    else
                        //        if (_fScripts.gvScripts.RowCount > 0)
                        //            _fScripts.gvScripts.MoveFirst();

                        RefreshOneWorkInfo();

                        //}
                        //finally
                        //{
                        //    _fScripts.gvScripts.EndUpdate();
                        //}

                        //RefreshOneScript();

                        UpdateMainControlsState();
                    }
                    catch (Exception ex)
                    {
                        //SERVER IS DOWN!! NEED RECONNECT                   
                        WriteError(ex.Message);
                        LoginToService();
                    }
                }
                finally
                {
                    _fWork.tlWork.EndUpdate();
                }
            }
            finally
            {
                EndWait();
                _fWork.tlWork.FocusedNodeChanged += tlWorkFocusedNodeChanged;
            }
        }

        private void tlWorkFocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            UpdateMainControlsState();
        }

        private void RefreshOneWorkInfo()
        {

        }

        private void rbiWorkStop_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
             string id = (string)_fWork.tlWork.FocusedNode.GetValue(3);
             string Entity = (string)_fWork.tlWork.FocusedNode.GetValue(2);

             string nameEntity = "Empty";
             switch (Entity)
             {
                 case "S": nameEntity = "session"; break;
                 case "T": nameEntity = "task"; break;
                 case "M": nameEntity = "script"; break;
             }

             if (MessageBox.Show(this, String.Format("Really stop {1} with id {0}?", id, nameEntity), String.Format("Stop {0}", nameEntity),
                 MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                 return;

             OperationResult or = new OperationResult(DM4Consts.Ok);
             switch (Entity)
             {
                 case "S": or = AbortSession(id); break;
                 case "T": or = AbortTask(id); break;
                 case "M": or = AbortScript(id); break;
             }

             if (!or)
                 MessageBox.Show(this, or.Message, DM4Consts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
             else
                 MessageBox.Show(this, String.Format("Stop command sended to {0}", nameEntity), String.Format("Stop {0}", nameEntity), MessageBoxButtons.OK, MessageBoxIcon.Information);

             RefreshWork();
        }

        private void rbiWorkStart_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string id = (string)_fWork.tlWork.FocusedNode.GetValue(3);
            string Entity = (string)_fWork.tlWork.FocusedNode.GetValue(2);

            string nameEntity = "Empty";
            switch (Entity)
            {
                case "S": nameEntity = "session"; break;
                case "T": nameEntity = "task"; break;
                case "M": nameEntity = "script"; break;
            }

            if (MessageBox.Show(this, String.Format("Really stop {1} with id {0}?", id, nameEntity), String.Format("Stop {0}", nameEntity),
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;

            OperationResult or = new OperationResult(DM4Consts.Ok);
            switch (Entity)
            {
                case "S": or = ResumeSession(id); break;
                case "T": or = ResumeTask(id); break;
                case "M": or = ResumeScript(id); break;
            }

            if (!or)
                MessageBox.Show(this, or.Message, DM4Consts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
                MessageBox.Show(this, String.Format("Resume command sended to {0}", nameEntity), String.Format("Stop {0}", nameEntity), MessageBoxButtons.OK, MessageBoxIcon.Information);

            RefreshWork();
        }
    }
}
